#!/usr/bin/env bash

RETVAL=0

platform=`uname`

http_domain=xxxx.service.worm.org

# 尝试创建安装目录
function _init_install() {
    mkdir -p /usr/local/worm
    mkdir -p /usr/local/worm/agent
    mkdir -p /usr/local/worm/agent/agent_srv
}

# 停止 agent
function stop_agent_srv() {
    # 停止当前版本
    control_file="/usr/local/worm/agent/agent_srv/control.sh"
    if [ -f "$control_file" ]; then
        ${control_file} stop
    fi
    echo 0
}

function restart_agent_srv() {
    # 停止当前版本
    control_file="/usr/local/worm/agent/agent_srv/control.sh"
    if [ -f "$control_file" ]; then
        ${control_file} stop
    fi

    # 下载安装包，并进行安装启动
    echo "install $max_version worm agent ..."
    cd /usr/local/worm/agent

    package_name=worm_agent..${max_version}.${platform}.tar.gz
    echo "getint package name: ${package_name}"

    rm ${package_name}
    sleep 1
    # https的方式
    wget --timeout=2 -t 3 https://${http_domain}:8122/worm/worm/${package_name} --no-check-certificate 2>/dev/null
    # 分析
    file_name=`echo ${package_name} | awk '{split($0, arr, ".");print arr[1];}'`
    echo ${file_name}
    file_version=`echo ${package_name} | awk '{split($0, arr, ".");print arr[2];}'`
    echo ${file_version}

    echo "install begin ..."
    # 创建安装目录
    mkdir -p ${file_version}
    mv ${package_name} ${file_version}/${package_name}
    cd ${file_version}
    tar -zxf ${package_name}

    ./control.sh start
    echo 0
}

function start_agent() {
    restart_agent
}

function use_help() {
    echo "$0 start|stop|restart [current_version]"
}

echo "**********************"
if [ "$1" == "" ]; then
    use_help                            # 帮助信息
elif [ "$1" == "stop" ];then
    stop_agent                          # 停止程序
elif [ "$1" == "start" ];then
    _init_install
    _get_max_version
    start_agent                         # 启动agent
elif [ "$1" == "restart" ];then
    _init_install
    _get_max_version
    restart_agent                       # 重启agent
else
    use_help
fi

RETVAL=$?

exit $RETVAL